package com.wangp.mywrite.inwork.pattern._7._7_1_look_around;

import com.google.common.collect.ImmutableList;
import com.wangp.mywrite.inwork.pattern.InitData;

/***
 * @author wangpeng
 * @since 2022-03-03  17:28
 */
public class LookAround {

    private static final String TITLE = "<TITLE> This is a title text </TITLE>";

    /**
     * <p>ABC01: $23.45         </p>
     * <p>HGG42: $5.21          </p>
     * <p>CFGG1: $899.00        </p>
     * <p>WXRZ6: $69.96         </p>
     * <p>Total items found: 4  </p>
     * 价格清单
     */
    private static final ImmutableList<String> PRICE_LIST = ImmutableList.<String>builder()
            .add("ABC01: $23.45 ")
            .add("HGG42: $5.21 ")
            .add("CFGG1: $899.00")
            .add("WXRZ6: $69.96 ")
            .build();

    public static void main(String[] args) {
        // 获取 title 中内容（不含标签）
        String titleReg = "(<[Tt][Ii][Tt][Ll][Ee]>)(.*?)(</[Tt][Ii][Tt][Ll][Ee]>)";
        String replaceReg = "$2";
        // This is a title text
        System.out.println(InitData.replaceByReg(TITLE, titleReg, replaceReg));

        // 提取url协议名称
        String httpReg = "(http.*?)(://)(.*)";
        String replaceReg2 = "$1";
        // [http, https, http?, http\, http/, httpss]
        System.out.println(InitData.replaceByReg(InitData.URL_LIST, httpReg, replaceReg2));

        // 向前查找（lookahead)
        // 模式 .+(?=:) 不包换':'
        String lookahead = "(.+)(?![https])";
        String url = "https://www.akulaku.com";
        // [https]
        System.out.println(InitData.find(url, lookahead));
        String lookbehind = "(?<=//)(.{2})";
        System.out.println(InitData.find(url, lookbehind));

        lookbehind();

        // 结合向前查找和向后查找
        lookaheadAndLookBehind();
    }

    private static void lookaheadAndLookBehind() {
        // 开头获取 title 里面内容的问题
        String reg = "(?<=<[Tt][Ii][Tt][Ll][Ee]>)(.*?)(?=</[Tt][Ii][Tt][Ll][Ee]>)";
        //
        System.out.println(InitData.find(TITLE, reg));
    }


    /**
     * <p>向后查找 </p>
     * <b>警告</b>
     * 向前查找模式的长度是可变的，它们可以包含．和+之类的元字符，所以它们非常灵活。 而向后查找模式只能是固定长度——这是一条几乎所有的正则表达式实现都遵守的限制。
     */
    private static void lookbehind() {
        // 找出所有的价格
        String priceReg = "\\$[0-9.]+";
        // [$23.45, $5.21, $899.00, $69.96]
        System.out.println(InitData.find(PRICE_LIST, priceReg));
        // 若不想出现 $
        String lookbehind = "(?<=\\$)[0-9.]+";
        System.out.println(InitData.find(PRICE_LIST, lookbehind));
    }

}
